package org.example.elasticsearch.query;

import co.elastic.clients.elasticsearch._types.query_dsl.Query;
import org.example.utils.Func;
import lombok.Getter;

import java.io.Serializable;
import java.util.LinkedList;

/**
 * @author: sql
 * @date: 2024/6/7
 * @Description: ES查询参数匹配类
 * @version: 1.0
 */
public class ESQueryShouldWrapper {

    @Getter
    private final LinkedList<Query> queries = new LinkedList<>();

    //1-默认：匹配一个，2-值得数量，3-匹配所有
    private int minShouldMatchType = 1;
    private int minShouldMatchNum = 0;
    private int countLikeNum = 0;

    /**
     * should中最小匹配百分比
     * 必须要先有should
     * 可以是具体数值如8，也可以是百分比如70%
     *
     * @return 自己
     */
    public String getMinShouldMatch() {
        if (Func.isEmpty(queries)) {
            return null;
        }
        return switch (minShouldMatchType) {
            case 3 -> String.valueOf(countLikeNum);
            case 2 -> String.valueOf(minShouldMatchNum);
            default -> "1";
        };
    }

    public ESQueryShouldWrapper minShouldMatchAll() {
        minShouldMatchType = 3;
        return this;
    }

    public ESQueryShouldWrapper minShouldMatchNum(Integer num) {
        if (Func.isNotEmpty(num) && num > 0) {
            this.minShouldMatchNum = num;
            minShouldMatchType = 2;
        }
        return this;
    }

    public ESQueryShouldWrapper like(Serializable value, String... fields) {
        if (Func.isNotEmpty(value) && Func.isNotEmpty(fields)) {
            for (String field : fields) {
                queries.add(Query.of(q -> q.wildcard(x -> x.field(field).value(String.format("*%s*", value)))));
            }
            countLikeNum++;
        }
        return this;
    }

}
